<script setup>
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter} from 'vue-router';
import { getPetDetailAPI, editPetAPI, addPetAPI, getBreedListAPI } from '@/apis/pet.js';
import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();
// 定义表单初始模板
const initialForm = {
    name: '',
    breedName: '',
    gender: '',
    status: 'AVAILABLE',
    description: '',
    story: '',
};

// 初始化表单（保持和初始模板一致）
const dialogForm = ref({ ...initialForm });

const breedList = ref([]); // 存储所有品种列表
const breedLoading = ref(false); // 品种列表加载状态

// 关闭对话框
const closeDialog = () => {
    router.push('/back');
};

// 获取品种列表
const getBreedList = async () => {
    // 已有数据/加载中则不重复请求
    if (breedList.value.length || breedLoading.value) return;
    breedLoading.value = true;
    try {
        const res = await getBreedListAPI(); 
        if (res.code === 1) {
            console.log(res);
            breedList.value = res.data.map(item => ({
                label: item.breedName, // 下拉框显示文本
                value: item.breedName  // 下拉框绑定值
            }));
        } else {
            ElMessage.error('获取品种列表失败');
        }
    } catch (err) {
        ElMessage.error('网络异常，获取品种列表失败');
        console.error(err);
    } finally {
        breedLoading.value = false;
    }
};

const currentScene = ref('add');
const initScene = async() => {
    const {type, id} = route.query;
    currentScene.value = type || 'add';
    // 重置表单
    Object.assign(dialogForm.value, initialForm);
    // 编辑时请求宠物信息
    if(currentScene.value === 'edit') {
        const res = await getPetDetailAPI(id);
        dialogForm.value = {
            ...res.data,
            description: res.data.description || '',
            story: res.data.story || ''
        };
    }
}

const petStatusSelectVal = [
    {
        label: '可领养',
        value: 'AVAILABLE',
    },
    {
        label: '已领养',
        value: 'UNAVAILABLE',
    },
];

const submitForm = async() => {
    // 基础校验：必填项
    if (!dialogForm.value.name) {
        return ElMessage.warning('请输入宠物名字');
    }
    if (!dialogForm.value.breedName) {
        return ElMessage.warning('请选择宠物品种');
    }
    if (!dialogForm.value.gender) {
        return ElMessage.warning('请选择宠物性别');
    }

    const baseParams = {...dialogForm.value};
    let res;
    // 添加宠物调用新增API
    if(currentScene.value === 'add') {
        console.log("baseParams:", baseParams);
        res = await addPetAPI(baseParams);
    }else {
        // 编辑宠物信息调用修改API
        baseParams.petId = route.query.id;
        res = await editPetAPI(baseParams);
    }
    if(res.code === 1) {
        ElMessage.success(currentScene === 'add' ? '添加宠物成功' : '修改宠物信息成功');
    }else {
        ElMessage.error('操作失败');
    }
    // 最后跳往宠物列表页面
    router.push('/back');
}

// 监听路由参数变化（比如从“添加”切到“编辑”）
watch([() => route.query.type, () => route.query.id], () => {
  initScene();
});
onMounted(() => initScene())
</script>
<template>
    <div class="dialog-content">
        <!-- 对话框头部 -->
        <div class="dialog-header">
            <strong class="dialog-title">{{ currentScene === 'add' ? '添加宠物' : '编辑宠物信息' }}</strong>
            <button class="close-btn" @click="closeDialog">
                <img src="/icon/x.png" alt="关闭图标" width="20px" height="20px">
            </button>
        </div>

        <!-- 添加宠物 -->
        <div class="dialog-form">
            <!-- 宠物资料 -->
            <div class="sub-title">
                <span class="sub-title-text">宠物资料</span>
            </div>
            <div class="info-container">
                <!-- 名字 -->
                <div class="info-row">
                    <div class="label">名字</div>
                    <el-input class="content" v-model="dialogForm.name" placeholder="输入名字"/>
                </div>
                <!-- 品种 -->
                <div class="info-row">
                    <div class="label">品种</div>
                    <div class="content"> 
                        <el-select 
                            v-model="dialogForm.breedName" 
                            placeholder="选择宠物品种"
                            @visible-change="(visible) => visible && getBreedList()"
                            :loading="breedLoading"
                        >
                            <el-option
                                v-for="item in breedList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </div>
                    <!-- <el-input class="content" v-model="dialogForm.breedName" placeholder="输入品种"/> -->
                </div>

                <!-- 性别 -->
                <div class="info-row">
                    <div class="label">性别</div>
                    <el-radio-group v-model="dialogForm.gender">
                        <el-radio value="MALE" size="large">公</el-radio>
                        <el-radio value="FEMALE" size="large">母</el-radio>
                    </el-radio-group>
                </div>

                <!-- 状态 -->
                <div class="info-row">
                    <div class="label">状态</div>
                    <div class="content">
                        <el-select v-model="dialogForm.status" placeholder="选择宠物状态">
                            <el-option
                                v-for="item in petStatusSelectVal"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </div>
                    
                </div>
                 <!-- 宠物描述 -->
                 <div class="info-row long info-text-area">
                    <div class="label">宠物描述</div>
                    <div class="content cont-textarea">
                        <el-input type="textarea"  v-model="dialogForm.description" placeholder="描述宠物的特点、性格等" />
                    </div>
                </div>
                <!-- 背景介绍 -->
                <div class="info-row long info-text-area">
                    <div class="label">背景介绍</div>
                    <div class="content cont-textarea">
                        <el-input type="textarea"  v-model="dialogForm.story" placeholder="描述宠物的背景故事、救助经历等" />
                    </div>
                </div>
            </div>         
        </div>
    </div>

    <!-- 底部按钮 -->
    <div class="dialog-footer">
        <el-button style="background-color: #F2F2F2;" @click="closeDialog">
            <span>取消</span>
        </el-button>
        <el-button @click="submitForm" style="background-color: #4077FB;color: #fff;">
            <span>保存</span>
        </el-button>
    </div>

</template>
<style scoped>
.dialog-content {
    padding: 0 24px;
}

.dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 70px;
    font-size: 18px;
}

.close-btn {
    background-color: transparent;
    border: 0;
    width: 20px;
    height: 20px;
    cursor: pointer;
}

.dialog-form {
    width: 100%;
    height: 100%;
    margin-top: 10px;
}

.sub-title {
    border-left: #58A3FE 3px solid;
}

.sub-title .sub-title-text {
    margin-left: 8px;
}

.info-container {
    margin-top: 24px;
    margin-left: 70px;
    width: calc(100% - 150px);
}

/* 单行信息 */
.info-row {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    width: 677px;
}
/* 单长行 */
.long {
    width: 100%;
}
.info-text-area {
    align-items: flex-start;
}

/* 并排信息 */
.double-row {
    display: flex;
    gap: 40px;
    width: 677px;
}

.info-item {
    display: flex;
    align-items: center;
    flex: 1;
}

.label {
    width: 96px;
    text-align: right;
    color: #787980;
    margin-right: 24px;
}

.content {
    flex: 1;
    background: #FAFAFA;
    padding: 8px 12px;
    border-radius: 4px;
    min-height: 28px;
    display: flex;
    align-items: center;
}
.cont-textarea {
    align-items: flex-start;
}

.input-inner {
    margin-left: 10px;
}

.dialog-footer {
    width: 372px;
    height: 45px;
    margin: 0 auto;
    margin-top: 31px;
    margin-bottom: 10px;
}

.dialog-footer .el-button {
    width: 76px;
    height: 100%;
}

/* 输入框聚焦样式 */
.input-box.focused {
    border: 1px solid #4077FB;
}

/* 输入框占位符颜色 */
:deep(.input-inner .el-input__inner)::placeholder {
    color: #AAB1BA;
}


/* 彻底清除当前页面el-input的默认样式 */
:deep(.content .el-input) {
  /* 清空Input组件外层容器的默认样式 */
  --el-input-hover-border-color: transparent !important;
  --el-input-focus-border-color: transparent !important;
}

/* 重置Input外层包装器（新结构的关键容器） */
:deep(.content .el-input__wrapper) {
  height: 100% !important; /* 输入框外层容器填满背景框高度 */
  border: none !important;
  box-shadow: none !important;
  background-color: transparent !important;
  padding: 0 !important;
  border-radius: 0 !important;
}

/* 重置核心输入框 */
:deep(.content .el-input__inner) {
  height: 100% !important; /* 输入框本身填满外层容器 */
  line-height: 100% !important; /* 文字行高与输入框高度一致 */
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
  background-color: transparent !important;
  padding: 0 !important;
  margin: 0 !important;
  height: 28px !important; /* 与.content的min-height对齐 */
  line-height: 28px !important;
  color: inherit !important; /* 继承父级文字颜色 */
}

/* 覆盖hover/focus状态的默认样式 */
:deep(.content .el-input__wrapper:hover),
:deep(.content .el-input__wrapper:focus-within) {
  border-color: transparent !important;
  box-shadow: none !important;
}

/* 清除输入框后缀图标（如清空按钮）（如需保留可删除） */
:deep(.content .el-input__suffix) {
  display: none !important;
}
/* 彻底清除textarea外层容器的所有默认样式 */
:deep(.content .el-textarea__wrapper) {
  border: none !important;
  box-shadow: none !important;
  background: transparent !important;
  padding: 0 !important;
  margin: 0 !important;
  border-radius: 0 !important;
  height: auto !important;
}

/* 清除textarea核心输入框的所有默认样式 */
:deep(.content .el-textarea__inner) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
  background: transparent !important;
  padding: 0 !important;
  margin: 0 !important;
  height: auto !important;
  line-height: inherit !important; /* 继承父级行高 */
  font-size: inherit !important; /* 继承父级字体大小 */
  color: inherit !important; /* 继承父级文字颜色 */
  resize: none !important; /* 禁止手动拖拽调整大小 */
  overflow: auto !important; 
}

/* 清除hover/focus状态的默认样式 */
:deep(.content .el-textarea__wrapper:hover),
:deep(.content .el-textarea__wrapper:focus-within) {
  border-color: transparent !important;
  box-shadow: none !important;
}

/* 隐藏滚动条 */
:deep(.content .el-textarea__inner::-webkit-scrollbar) {
  display: none !important;
}
:deep(.content .el-textarea__inner) {
  -ms-overflow-style: none !important; /* IE/Edge */
  scrollbar-width: none !important; /* Firefox */
}

/* 让下拉框和输入框样式统一：清除默认边框、背景、箭头 */
:deep(.content .el-select) {
  /* 覆盖Element UI的默认变量，去掉边框相关样式 */
  --el-select-border-color: transparent;
  --el-select-hover-border-color: transparent;
  --el-select-focus-border-color: transparent;
}

/* 清除下拉框外层容器的样式 */
:deep(.content .el-select__wrapper) {
  border: none !important;       /* 去掉边框 */
  box-shadow: none !important;   /* 去掉阴影 */
  background-color: transparent !important; /* 继承content的浅色背景 */
  padding: 0 !important;         /* 去掉默认内边距 */
}

/* 清除输入框（下拉框文本区域）的样式 */
:deep(.content .el-select__input) {
  border: none !important;       /* 去掉输入框边框 */
  outline: none !important;      /* 去掉聚焦轮廓 */
  background-color: transparent !important; /* 透明背景 */
  padding: 0 !important;         /* 去掉内边距 */
  margin: 0 !important;          /* 去掉外边距 */
}
</style>